package com.hy.common;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import java.io.IOException;

@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.host:localhost:9200}")
    private String esHost;

    @Bean
    public RestHighLevelClient elasticsearchClient() {
        return new RestHighLevelClient(
                RestClient.builder(HttpHost.create(esHost))
        );
    }

    @PreDestroy
    public void close() throws IOException, IOException {
        if (this.elasticsearchClient() != null) {
            this.elasticsearchClient().close();
        }
    }
}